import { withAuth } from "next-auth/middleware"
import { NextResponse } from "next/server"
import { getToken } from 'next-auth/jwt'
import { UserRole } from '@/types'

export default withAuth(
  async function middleware(req) {
    const token = await getToken({ req })
    const path = req.nextUrl.pathname

    console.log('当前路径:', path)
    console.log('当前用户的 token:', token)

    // 如果已登录用户访问登录页或根路径，重定向到仪表板
    if ((path === '/login' || path === '/') && token) {
      return NextResponse.redirect(new URL('/dashboard', req.url))
    }

    // 如果未登录用户访问受保护路由，重定向到登录页
    if (path.startsWith('/dashboard') && !token) {
      return NextResponse.redirect(new URL('/login', req.url))
    }

    // 检查角色权限
    if (path.startsWith('/dashboard/employees') && 
        token?.role !== UserRole.ADMIN && token?.role !== UserRole.MANAGER) {
      return NextResponse.redirect(new URL('/dashboard', req.url))
    }

    return NextResponse.next()
  },
  {
    callbacks: {
      authorized: ({ token }) => !!token
    },
  }
)

export const config = {
  matcher: ['/', '/dashboard/:path*']
}